/* eslint-disable no-underscore-dangle,no-param-reassign */
import axios from 'axios'
import statusCode from './statusCode'
// import { getCookie } from "./cookie";
let LOGIN_OVERTIME = false

function http() {
  const request = axios.create({
    baseURL: process.env.VUE_APP_API_BASE_URL,
    timeout: 50000
  })
  request.interceptors.request.use((theRequest) => {
    // theRequest.headers.common.Authorization = getCookie("token");
    theRequest.params = { ...theRequest.params, _t: Date.now() }
    return theRequest
  })

  request.interceptors.response.use(
    (response) => {
      const { code, message } = response.data
      if (code === statusCode.SUCCESS) {
        return response.data
      }
      const error = new Error(message || '访问人数太多，请刷新试试')
      error.code = code
      error.result = response.data.result
      if (response.config.url.indexOf('/auth/login')) {
        return response.data
      }
      throw error
    },
    (error) => {
      let message = '当前访问人数太多，请刷新试试'
      let code = 500
      const { response, code: _code } = error
      if (response && response.status) {
        code = response.status
        if (code === statusCode.LOGIN_OVERTIME) {
          message = '登录超时，请重新登录'
        } else if (code === statusCode.NOT_POWER) {
          message = '无权限操作'
        } else if (code === statusCode.NOT_PATH) {
          message = '接口路径异常'
        } else if (code === statusCode.INTER_ERROR) {
          message = '后端网关服务异常，请重试!'
        } else if (code === statusCode.SERVER_ERROR) {
          // message = '服务异常!';
          if (response.data.message) {
            message = response.data.message
          } else {
            message = '服务异常!'
          }
        }
      }
      if (_code === statusCode.ECONNABORTED) {
        message = '服务连接超时'
      }
      const _error = new Error(message)
      _error.code = code
      throw _error
    }
  )
  return request
}

export default http()
